package net.fdukedom.epicurus.presentation.filters;

import net.fdukedom.epicurus.presentation.SessionData;
import net.fdukedom.epicurus.domain.entity.User;
import net.fdukedom.epicurus.domain.entity.AccessRule;
import net.fdukedom.epicurus.domain.util.GroupHelper;
import net.fdukedom.epicurus.security.AccessChecker;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Checks that user is logged in.
 *
 * @author Dmitry Y. Kochelaev
 */
public class CheckRoleFilter extends AbstractHttpFilter {

    /**
     * Login page url.
     */
    private String redirectPage;

    private AccessChecker accessChecker = AccessChecker.getInstance();

    @Override
    public void init(FilterConfig config) {
        super.init(config);
        redirectPage = config.getInitParameter("redirectPage");
    }

    protected void doFilter(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws IOException, ServletException{
        boolean loggedIn = true;
        String path = request.getServletPath();
        String actionName = path.substring(0, path.lastIndexOf("."));
        User user = SessionData.getInstance(request).getUser();
        if (user == null) {
            loggedIn = false;
            user = new User();
            user.getGroups().add(GroupHelper.getInstance().findByName("guests"));
            user.getGroups().add(GroupHelper.getInstance().findByName("allUsers"));
        }
        request.setAttribute("isLoggedIn", loggedIn);

        if (accessChecker.hasAccess(user, actionName, AccessRule.EXECUTE)) {
            filterChain.doFilter(request, response);
        } else {
            StringBuilder redirectLink = new StringBuilder();
            for (int i = 1; i < actionName.length(); ++i) {
                if (actionName.charAt(i) == '/') {
                    redirectLink.append("../");
                }
            }
            redirectLink.append(redirectPage);
            response.sendRedirect(redirectLink.toString());
        }
    }
}
